<template>
	<div class="search-container">
		<!-- 导航栏 -->
		<TmallNavBar>
			<template #left><i class="icon iconfont icon-zuojiantou"></i></template>
			<template #default>商品搜索</template>
			<template #right>
				<i class="icon iconfont icon-shouye1" @click="$router.push({path: '/'})"></i>
			</template>
		</TmallNavBar>

		<!-- 搜索商品盒子 -->
		<div class="goods-search-box">
			<div class="search-bar">
				<van-search
					placeholder="请输入商品"
					shape="round"
					background="#27BA9B"
					v-model="keyword"
					style="width: 85%;"
					@update:model-value="inputHandler"
				/>

				<div @click="gotoGoodsList(keyword)" class="search-btn">搜索</div>
			</div>
		</div>
		
		<!-- 搜索建议 -->
		<div class="sugg-list" v-if="searchResults.length != 0">
			<div class="sugg-item" v-for="(item,index) in searchResults" :key="index" @click="gotoGoodsList(item.value)">
				<div class="goods-name">{{item.value}}</div>
				<van-icon name="arrow" size="16" />
			</div>
		</div>
		
		<!-- 搜索历史 -->
		<div class="history-box" v-else>
			<div class="history-title">
				<span>搜索历史</span>
				<van-icon name="delete-o" size="20" @click="clearHistory" />
			</div>
			
			<div class="history-list">
				<van-row class="demo-uni-row">
					<van-col :span="8" v-for="(item, index) in goodsSearchHistorys" :key="index">
						<div class="history-item" @click="gotoGoodsList(item)">
							{{item}}
						</div>
					</van-col>
				</van-row>
			</div>
		</div>

		<!-- 热门推荐 -->
		<div class="scroll" style="height: 100vh">
			<div>
				<div class="caption" :style="`margin-top: ${marginTop}px`">
					<span class="text">热门推荐</span>
				</div>

				<!-- 骨架屏 -->
                <!-- <van-skeleton v-if="isShowSkeleton">
                    <template #template>
                        <div class="skeleton-goods-list">
                            <div class="skeleton-goods-item" v-for="(item) in 2" :key="item" >
                                <div class="image-box" style="margin-bottom: 5px;">
                                    <van-skeleton-image class="thumb" style="width: 100%;"/>
                                </div>
                                <div>
                                    <van-skeleton-paragraph style="height: 30px;margin-bottom: 10px;"/>
                                    <div class="skeleton-price-box">
                                        <van-skeleton-paragraph row-width="40%"/>
                                        <van-skeleton-paragraph row-width="40%"/>
                                    </div>
                                    <van-skeleton-paragraph row-width="40%" style="float: right;margin-top: 10px;"/>
                                </div>
                            </div>
                        </div>
                    </template>
                </van-skeleton> -->

				<!-- <div v-else> -->
					<div class="hot-goods">
						<template v-for="(item, index) in hotGoodsList" :key="index">
							<TmallGoodsItem :goods="item" />
						</template>
					</div>

					<div :style="`height: ${scrollHeight}px`"></div>
				<!-- </div> -->
			</div>
		</div>
		
		<!-- 返回顶部组件 -->
        <TmallBackTop @backTop="backTop" :isShowBackTop="isShowBackTop" />
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue"
import { useRouter } from 'vue-router'
import { reqGetGoodsListAPI, reqSearchSuggestCompletionAPI } from "@/apis/goods"
import BScroll from 'better-scroll'
import { reactive } from "vue";

// 搜索关键字
const keyword = ref('')

// 路由器
const router = useRouter()

// 延时器
const timer = ref(null)

// 推荐搜索列表
const searchResults = ref([])

// 输入事件处理
const inputHandler = (value) => {
	console.log('inputHandler value =', value);
	// ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
	// 重新启动延时器
	timer.value = setTimeout(() => {
		keyword.value = value
		getSearchList()
	}, 500)
}



// ----------------------- 返回顶部开始 -----------------------
const isShowBackTop = ref(false)
const backTop = () => {
    bscroll.scrollTo(0, 0, 500);
}
// ----------------------- 返回顶部结束 -----------------------






// ------------------------------- 跳转到商品列表功能开始 -------------------------------
const gotoGoodsList = (keyword) => {
	router.push({path: '/goodsList', query: {"keyword": keyword}})
}
// ------------------------------- 跳转到商品列表功能开始 -------------------------------






let bscroll = reactive({})

// 是否显示骨架屏
const isShowSkeleton = ref(false)

onMounted( async() => {
	isShowSkeleton.value = true
	goodsSearchHistoryList.value = JSON.parse(localStorage.getItem('GOODS_SEARCH_HISTORY') || '[]')

	// 获取热门商品列表
	await getHotGoodsList()

	isShowSkeleton.value = false

	bscroll = new BScroll(document.querySelector('.scroll'), {
        probeType: 3,
        click: true,
    })

    // 监听滚动
    bscroll.on('scroll',(position) => {
        isShowBackTop.value = -position.y > 70;
    });
})

// 根据搜索关键词,搜索商品建议列表
const getSearchList = async () => {
	if (keyword.value == '') {
		searchResults.value = []
		return
	}
	
	const result = await reqSearchSuggestCompletionAPI(keyword.value)
	searchResults.value = result.data.search_suggests != null ? result.data.search_suggests : []
	
	saveGoodsSearchHistory()
}





// ------------------------------- 商品搜索历史功能开始 -------------------------------
// 商品搜索历史列表
const goodsSearchHistoryList = ref([])

// scrolldiv 高度
const scrollHeight = ref(0)

const marginTop = computed(() => {
	return Math.ceil(goodsSearchHistoryList.value.length/3) * 25 + 60
})

// 商品搜索历史计算属性
let goodsSearchHistorys = computed(() => {  
	// 设置 scroll div 高度
	scrollHeight.value = Math.ceil(goodsSearchHistoryList.value.length/3) * 25 + 170
	return [...goodsSearchHistoryList.value].reverse()
})

// 保存商品搜索历史
const saveGoodsSearchHistory = () => {
	// 当搜索历史个数大于9则需要删除最旧的历史
	if (goodsSearchHistoryList.value.length >= 9) {
		goodsSearchHistoryList.value.shift()
	}
	
	if(goodsSearchHistoryList.value.indexOf(keyword.value) == -1) {
		goodsSearchHistoryList.value.push(keyword.value)
	}
	
	// 商品搜索历史持久化存储
	localStorage.setItem('GOODS_SEARCH_HISTORY', JSON.stringify(goodsSearchHistoryList.value))
}

// 清空商品搜索历史
const clearHistory = () => {
	localStorage.removeItem('GOODS_SEARCH_HISTORY')
	goodsSearchHistoryList.value = []
	scrollHeight.value = 170
	marginTop.value = 60
}
// ------------------------------- 商品搜索历史功能结束 -------------------------------





// ------------------------------- 获取热门商品功能开始 -------------------------------
const hotGoodsList = ref([])
const getHotGoodsList = async () => {
	const result = await reqGetGoodsListAPI({status: 1, is_hot: 1})
	hotGoodsList.value = result.data.goods != null ? result.data.goods : []
}
// ------------------------------- 获取热门商品功能结束 -------------------------------
</script>

<style lang="scss" scoped>
.skeleton-goods-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    .skeleton-goods-item {
        width: 48%;
        padding: 10px;
        margin-top: 10px;
        border-radius: 5px;
        background-color: #fff;
        .image {
            width: 154px;
            height: 154px;
        }
        .skeleton-price-box {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
        }
        .name {
            height: 30px;
            font-size: 13px;
        
            overflow:hidden;
            text-overflow:ellipsis;
            display:-webkit-box;
            -webkit-box-orient:vertical;
            -webkit-line-clamp:2;
        }
        .price {
            margin-top: 8px;
            line-height: 1;
            color: #cf4444;
            font-size: 15px;
        }
        .symbol {
            font-size: 70%;
        }
        .decimal {
            font-size: 70%;
        }
    }
}

.search-container {
	height: 100vh;
	width: 100%;
	background-color: ghostwhite;
    margin-top: 44px;
	position: fixed;

	// 搜索商品盒子
	.goods-search-box {
		position: relative;
		width: 100%;
		z-index: 100;
		.search-bar {
			display: flex;
			justify-content: center;
			align-items: center;
			background: #27BA9B;
			.search-btn {
				color: white;
				border: 1px solid white;
				padding: 6px 12px;
				border-radius: 3px;
				margin-right: 4px;
			}
		}
	}

	// 搜索建议
	.sugg-list {
		position: fixed;
		width: 100%;
		padding: 0 5px;
		z-index: 100;
		background: white;
		.sugg-item {
			padding: 13px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.goods-name {
				// 文字不允许换行
				white-space: nowrap;
				// 溢出部分隐藏
				overflow: hidden;
				// 文本溢出使用...代替
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}
	}

	// 搜索历史
	.history-box {
		padding: 1px 15px 10px 10px;
		background: white;
		position: fixed;
		width: 100%;
		z-index: 100;
		.history-title {
			display: flex;
			justify-content: space-between;
			height: 40px;
			align-items: center;
			font-size: 13px;
			border-bottom: 1px solid gainsboro;
		}
		.history-list {
			display: flex;
			flex-direction: column;
			margin-top: 5px;
			.history-item {
				margin-top: 5px;
				margin-right: 5px;
				background-color: gainsboro;
				text-align: center;
				color: white;
				border-radius: 4px;
				padding: 3px;

				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
			}
		}
	}

	// 热门推荐
	.scroll {
		background-color: ghostwhite;
		.caption {
			display: flex;
			justify-content: center;
			line-height: 1;
			padding: 18px 0 20px;
			font-size: 16px;
			color: #262626;
			.span {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 0 14px 0 15px;

				&::before,
				&::after {
					content: '';
					width: 10px;
					height: 10px;
					background-image: url(@/assets/images/hot.png);
					background-size: contain;
					margin: 0 5px;
				}
			}
		}

		.hot-goods {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			padding: 0 10px;
		}
	}
}
</style>